<?php
namespace app\admin\controller;

use think\Config;
class GetDb extends Base{
 
   public function __construct(){
	    parent::__construct();
        $active['extend']['getDb'] = 1;
        $this->view->active = $active;
   }
   
   
    public function index() {
		
        $DataDir = "databak/";
        if(!file_exists($DataDir)){
		  mkdir($DataDir);
		}
        $lists = $this->MyScandir('databak/');
        $this->view->assign("datadir",$DataDir);
        $this->view->assign("lists",$lists);
        return $this->view->fetch();
    }
   

	public function backup(){

		$mr= $this->download_backup();
		$mr->backup();	
		return $this->success('备份成功', U('GetDb/index',array('method'=>"index")));
	}

	 public function del(){
		$mr= $this->download_backup();
		$DataDir = "databak/";
		
	
		if (@unlink($DataDir.$_GET['name'])) {
          return $this->success('删除成功', U('GetDb/index'));
         }else {
          return $this->success('删除失败', U('GetDb/index'));
         }	 
	 }
	 /**
	  *  数据库备份还原
	  */
	  public function restore()
	  {
		  $mr= $this->download_backup();
		  $DataDir = "databak/";
		  $mr->recover($_GET['name']);
		  return $this->success('备份成功', U('GetDb/index',array('method'=>"index")));
	  }
	  
	  
	  
	 /**
	  *  数据库备份下载
	  */
	 public function down()
	 {
	   $DataDir = "databak/";
       $down = $this->downloadFile($DataDir.$_GET['name']);
            
	 }
	  
	 private function download_backup()
	 {
		 $DataDir = "databak/";
		  $config = array(
                'host' => Config::get('database.hostname'),
                'port' => '3306',
                'userName' => Config::get('database.username'),
                'userPassword' => Config::get('database.password'),
                'dbprefix' => Config::get('database.prefix'),
                'charset' => Config::get('database.charset'),
                'path' => $DataDir,
                'isCompress' => 0,
                'isDownload' => 0
            );
		 $mr = new \org\MySQLReback($config);
		 $mr->setDBName('qingyuanbao');
		 $lists = $this->MyScandir('databak/');
		 $this->view->assign("datadir",$DataDir);
		 $this->view->assign("lists",$lists);
		 return $mr;
	 }
	 
	 
	
    private function MyScandir($FilePath = './', $Order = 0) {
        $FilePath = opendir($FilePath);
        while (false !== ($filename = readdir($FilePath))) {
            $FileAndFolderAyy[] = $filename;
        }
        $Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
        return $FileAndFolderAyy;
    }
	
	private function downloadFile($fileName) {
		ob_end_clean();
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header('Content-Length: ' . filesize($fileName));
		header('Content-Disposition: attachment; filename=' . basename($fileName));
		readfile($fileName);
    }

   //备份还原数据库
    
   
}
